/*
 * @Description:
 * @Author: Rfan
 * @Date: 2022-04-28 13:48:21
 * @LastEditTime: 2022-10-24 18:17:03
 */

import { useEffect, useMemo, useState } from 'react';
import { Button, Popconfirm, Progress, Space, Table, Typography } from 'antd';
import classNames from 'classnames/bind';
import { observer } from 'mobx-react-lite';
import { CheckCircleFilled } from '@ant-design/icons';
import { viewTestReport } from '@/api/standardizedDetection/detectionTask';
import { formatDate, isNullObj } from '@/utils';
import { useFormatMessage } from '@/utils/intlHelpers';
import { wsState } from '@/store/WSStore';
import { useStandardizedDetectionContext } from '../contexts/StandardizedDetectionContext';
import DetectionResult from '@/components/ArchivesDetection/Result';
import InspectionTasks from '@/components/ArchivesDetection';
import UploadOrigin from './dialogs/UploadOrigin';
import UploadEEP from './dialogs/UploadEEP';
import UploadCD from './dialogs/UploadCD';
import UploadFolder from './dialogs/UploadFolder';
import DetectExecuting from '@/components/ArchivesDetection/conponentes/DetectExecuting';
import styles from '../styles/pageList.module.scss';
import UploadSip from './dialogs/UploadSip';

const cx = classNames.bind(styles);

const { Column } = Table;

const PageList = (props: any) => {
  const { className } = props;
  const {
    StandardizedList,
    selectItems,
    setActiveStandardized,
    activeStandardized,
    performDetection,
    setDetectionItemProcess,
    getInspectionList,
    updateStandardizedList,
    setSelectKey,
    deleteItem,
    stateFilter,
    detectionFilter,
    selectFondId,
    selectAT,
    selectATId,
    editStandardizedList
  } = useStandardizedDetectionContext();
  const formatMessage = useFormatMessage();

  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  // 表格数据
  const [reportList, setReportList] = useState({});
  // 修改弹窗显示
  const [createInspectionTasksVisible, setCreateInspectionTasksVisible] = useState(false);
  // 修改弹窗内容
  const [taskValue, setTaskValue] = useState({});

  const [listQuery, setListQuery] = useState({
    pageNo: 1,
    pageSize: 10,
    param: {}
  });
  // 上传文件弹窗显示标志
  const [detectionResultVisible, setDetectionResultVisible] = useState(false);
  // 上传原文弹窗显示标志
  const [uploadOriginVisible, setUploadOriginVisible] = useState(false);
  // 上传EEP包弹窗显示标志
  const [uploadEEPVisible, setUploadEEPVisible] = useState(false);
  // 上传CD包弹窗显示标志
  const [uploadCDVisible, setUploadCDVisible] = useState(false);
  // 上传条目弹窗显示标志
  const [uploadFolderVisible, setUploadFolderVisible] = useState(false);
  // 开始检测弹窗
  const [detectExecutingVisible, setDetectExecutingVisible] = useState(false);

  useEffect(() => {
    if (selectATId) {
      setListQuery({
        pageNo: 1,
        pageSize: 10,
        param: {
          archiveTypeId: selectATId
        }
      });
    }
  }, [selectATId]);

  useEffect(() => {
    if (listQuery && !isNullObj(listQuery.param)) {
      setLoading(true);

      getInspectionList(listQuery)
        .then((res: any) => {
          setTotal(res?.totalCount);
          setTimeout(() => {}, 2000);
        })
        .finally(() => {
          setLoading(false);
        });
    }
  }, [listQuery]);

  /**
   * 监听ws消息更改进度
   */
  useEffect(() => {
    const { archiveDetection } = wsState;
    if (archiveDetection) {
      setDetectionItemProcess(archiveDetection);
    }
  }, [wsState.archiveDetection]);

  /**
   * @description 切换页码触发
   * @param {number} page 页码
   * @param {number} pageSize 每页条目数
   */
  const pageChange = (page: number, pageSize: number) => {
    setListQuery((state) => ({
      ...state,
      pageNo: page,
      pageSize
    }));
  };

  /**
   * @description : 表格选项相关设置
   * @param {number} selectedRowKeys 选择的项目的KEY
   */
  const onSelectChange = (selectedRowKeys: number[]) => {
    setSelectKey(selectedRowKeys);
  };

  /**
   * @description:  表格多选配置
   */
  const rowSelection = {
    selectItems,
    onChange: onSelectChange
  };

  /**
   * @description: 关闭检测报告弹窗
   */
  const closeDetectionResultDialog = () => {
    setDetectionResultVisible(false);
  };

  /**
   * @description: 打开上传目录弹窗
   * @param {any} item
   * @return {void}
   */
  const showUploadOriginDialog = (item: any): void => {
    setActiveStandardized(item);
    setUploadOriginVisible(true);
  };

  /**
   * @description: 关闭上传目录弹窗
   * @param {any} record
   * @return {void}
   */
  const closeUploadOriginDialog = (record: any): void => {
    setUploadOriginVisible(false);
    setActiveStandardized({});
    if (record) {
      updateStandardizedList(record);
    }
  };

  /**
   * @description: 打开上传EEP包目录弹窗
   * @param {any} item
   * @return {void}
   */
  const showUploadEEPDialog = (item: any): void => {
    setActiveStandardized(item);
    setUploadEEPVisible(true);
  };

  /**
   * @description: 关闭上传目录弹窗
   * @param {any} record
   * @return {void}
   */
  const closeUploadEEPDialog = (record: any): void => {
    setUploadEEPVisible(false);
    setActiveStandardized({});
    if (record) {
      updateStandardizedList(record);
    }
  };

  /**
   * @description: 打开上传CD包目录弹窗
   * @param {any} item
   * @return {void}
   */
  const showUploadCDDialog = (item: any): void => {
    setActiveStandardized(item);
    setUploadCDVisible(true);
  };

  /**
   * @description: 关闭上传目录弹窗
   * @param {any} record
   * @return {void}
   */
  const closeUploadCDDialog = (record: any): void => {
    setUploadCDVisible(false);
    setActiveStandardized({});
    if (record) {
      updateStandardizedList(record);
    }
  };

  /**
   * @description: 打开上传CD包目录弹窗
   * @param {any} item
   * @return {void}
   */
  const showUploadFolderDialog = (item: any): void => {
    setActiveStandardized(item);
    setUploadFolderVisible(true);
  };

  /**
   * @description: 关闭上传目录弹窗
   * @param {any} record
   * @return {void}
   */
  const closeUploadFloderDialog = (record: any): void => {
    setUploadFolderVisible(false);
    setActiveStandardized({});
    if (record) {
      updateStandardizedList(record);
    }
  };

  /* 再次检测 */
  // const uploadFileFunc = (id: number) => {
  //   uploadStandardized(id).then((res: any) => {
  //     console.log('再次检测', res.data);
  //   });
  // };

  /**
   * @description: 根据传入的列表判断按钮是否展示
   * @param {number[]} allowList 允许展示的状态列表
   * @param {number} state 当前的状态
   * @return {boolean} 是否可以展示
   */
  const showBtnFunc = (allowList: number[], state: number): boolean => {
    if (!state) return allowList.indexOf(0) >= 0;
    return allowList.indexOf(state) >= 0;
  };

  const getItemListState = (list: any[]): boolean => {
    let _state = false;
    list.forEach((item) => {
      if (item.status) {
        _state = item.status;
      }
    });
    return _state;
  };

  const getOriginState = (item: any): boolean => {
    return item.attOriginal?.status;
  };

  const clickReport = (item: any) => {
    viewTestReport(item.id).then((res) => {
      const { data } = res;
      setReportList(data);
    });
    setDetectionResultVisible(true);
  };

  const startTesting = (id: any) => {
    setDetectExecutingVisible(true);
    performDetection(id);
  };

  return (
    <div className={className}>
      <Table
        dataSource={StandardizedList}
        loading={loading}
        rowKey="id"
        rowSelection={rowSelection}
        bordered
        scroll={{ x: 'max-content' }}
        pagination={{
          current: listQuery.pageNo,
          pageSize: listQuery.pageSize,
          total,
          onChange: pageChange
        }}
      >
        <Column title="序号" dataIndex="id" key="id" align="center" />
        <Column title="档案类型" dataIndex="archiveTypeName" key="archiveTypeName" align="center" />
        <Column title="任务名称" dataIndex="name" key="taskName" align="center" />
        <Column
          title="检测类型"
          key="check_type"
          align="center"
          render={(_val, record: any) => `${detectionFilter(record.detectionType)}检测`}
        />
        <Column
          title="创建时间"
          dataIndex="createTime"
          key="createTime"
          align="center"
          width={120}
          render={(text) => <span>{formatDate(text)}</span>}
        />
        <Column title="检测模板" dataIndex="templateName" key="templateName" align="center" />

        <Column
          title="被检测文件"
          key="detectedFiles"
          align="center"
          render={(_val, record: any) => (
            <>
              <div>
                {record.detectionType === 6 ? (
                  '仅对系统环境检测，无需上传附件'
                ) : record.detectionType === 1 ? (
                  <>
                    <div>
                      <Space>
                        <div className={cx('attach--item')}>
                          条目 |{' '}
                          {getItemListState(record.attItemsList) ? (
                            <Typography.Text type="success">
                              <CheckCircleFilled />
                            </Typography.Text>
                          ) : (
                            <Typography.Text type="warning">待上传</Typography.Text>
                          )}
                        </div>
                        <Button
                          size="small"
                          type="link"
                          onClick={() => {
                            showUploadFolderDialog(record);
                          }}
                          disabled={showBtnFunc([3, 4, 5], record.status)}
                        >
                          管理
                        </Button>
                      </Space>
                    </div>
                    <div>
                      <Space>
                        <div className="attach--origin">
                          原文 |{' '}
                          {getOriginState(record) ? (
                            <Typography.Text type="success">
                              <CheckCircleFilled />
                            </Typography.Text>
                          ) : (
                            <Typography.Text type="warning">待上传</Typography.Text>
                          )}
                        </div>
                        <Button
                          size="small"
                          type="link"
                          onClick={() => {
                            showUploadOriginDialog(record);
                          }}
                          disabled={showBtnFunc([3, 4, 5], record.status)}
                        >
                          管理
                        </Button>
                      </Space>
                    </div>
                  </>
                ) : (
                  <Space>
                    {showBtnFunc([3, 4, 5], record.detectionType) ? (
                      <div className={cx('attach--item')}>
                        {detectionFilter(record.detectionType)} |{' '}
                        {getOriginState(record) ? (
                          <Typography.Text type="success">
                            <CheckCircleFilled />
                          </Typography.Text>
                        ) : (
                          <Typography.Text type="warning">待上传</Typography.Text>
                        )}
                      </div>
                    ) : (
                      <div className={cx('attach--item')}>
                        {detectionFilter(record.detectionType)} |{' '}
                        {getItemListState(record.attItemsList) ? (
                          <Typography.Text type="success">
                            <CheckCircleFilled />
                          </Typography.Text>
                        ) : (
                          <Typography.Text type="warning">待上传</Typography.Text>
                        )}
                      </div>
                    )}

                    <Button
                      size="small"
                      type="link"
                      onClick={() => {
                        if (record.detectionType === 2) {
                          showUploadFolderDialog(record);
                        }
                        if (record.detectionType === 3) {
                          showUploadOriginDialog(record);
                        }
                        if (record.detectionType === 4) {
                          showUploadEEPDialog(record);
                        }
                        if (record.detectionType === 5) {
                          showUploadCDDialog(record);
                        }
                      }}
                      disabled={showBtnFunc([3, 4, 5], record.status)}
                    >
                      管理
                    </Button>
                  </Space>
                )}
              </div>
            </>
          )}
        />
        <Column
          title="检测时间"
          dataIndex="startTime"
          key="startTime"
          align="center"
          width={120}
          render={(text) => <span>{formatDate(text)}</span>}
        />
        <Column
          title="检测完成时间"
          dataIndex="endTime"
          key="endTime"
          align="center"
          width={120}
          render={(text) => <span>{formatDate(text)}</span>}
        />
        <Column
          title="状态"
          dataIndex="status"
          key="status"
          align="center"
          render={(status: number, record: any) => (
            <>
              {record.progress && record.progress < 100 && (
                <Progress percent={record.progress} steps={5} size="small" />
              )}
              {stateFilter(status)}
            </>
          )}
        />

        <Column
          title={formatMessage('tableAction')}
          key="action"
          className={cx('action-col')}
          align="center"
          width={140}
          render={(_text, record: any) => (
            <Space>
              {/* {showBtnFunc([4], record.status) && (
                <Button
                  type="link"
                  size="small"
                  onClick={() => {
                    uploadFileFunc(record.id);
                  }}
                >
                  再次检测
                </Button>
              )} */}
              {showBtnFunc([0, 1], record.status) && (
                <Button
                  type="link"
                  size="small"
                  onClick={() => {
                    setCreateInspectionTasksVisible(true);
                    setTaskValue(record);
                  }}
                >
                  编辑
                </Button>
              )}
              {showBtnFunc([1], record.status) && (
                <Button type="link" size="small" onClick={() => startTesting(record.id)}>
                  执行检测
                </Button>
              )}
              {showBtnFunc([0, 1, 3, 4], record.status) && (
                <Button
                  type="link"
                  size="small"
                  danger
                  onClick={() => {
                    deleteItem(record.id);
                  }}
                >
                  删除
                </Button>
              )}
              {showBtnFunc([2], record.status) && (
                <Popconfirm title="确定要取消检测吗？" okText="是" cancelText="否">
                  <Button type="link" size="small">
                    取消检测
                  </Button>
                </Popconfirm>
              )}
            </Space>
          )}
        />
        <Column
          title="报告"
          key="report"
          align="center"
          render={
            (_text, record: any) =>
              // record.status ? (
              //   <Button onClick={() => setDetectionResultVisible(true)}>《检测报告》</Button>
              // ) : (
              //   ''
              // )
              showBtnFunc([3, 4], record.status) && (
                <Button type="link" onClick={() => clickReport(record)}>
                  《检测报告》
                </Button>
              )
            // <Button type="link" onClick={() => clickReport(record)}>
            //   《检测报告》
            // </Button>
          }
        />
      </Table>

      {useMemo(
        () => (
          <DetectExecuting
            visible={detectExecutingVisible}
            onClose={() => {
              setDetectExecutingVisible(false);
            }}
          />
        ),
        [detectExecutingVisible]
      )}

      {/* 检测报告弹窗 */}
      {useMemo(
        () =>
          !isNullObj(reportList) && (
            <DetectionResult
              list={reportList}
              visible={detectionResultVisible}
              onClose={closeDetectionResultDialog}
            />
          ),
        [detectionResultVisible, reportList]
      )}

      {/* 检测任务弹窗 */}
      {useMemo(
        () => (
          <InspectionTasks
            visible={createInspectionTasksVisible}
            onClose={() => {
              setCreateInspectionTasksVisible(false);
            }}
            data={taskValue}
            editStandardizedList={editStandardizedList}
            archiveType={selectFondId}
          />
        ),
        [createInspectionTasksVisible]
      )}

      {/* 上传原文弹窗 */}
      {useMemo(
        () => (
          <UploadOrigin visible={uploadOriginVisible} onClose={closeUploadOriginDialog} />
        ),
        [uploadOriginVisible, activeStandardized]
      )}

      {/* 上传EEP包弹窗 */}
      {useMemo(
        () => (
          <UploadSip visible={uploadEEPVisible} onClose={closeUploadEEPDialog} />
        ),
        [uploadEEPVisible, activeStandardized]
      )}

      {/* 上传光盘格式包上传弹窗 */}
      {useMemo(
        () => (
          <UploadCD visible={uploadCDVisible} onClose={closeUploadCDDialog} />
        ),
        [uploadCDVisible, activeStandardized]
      )}

      {/* 上传条目上传弹窗 */}
      {useMemo(
        () => (
          <>
            {selectAT !== {} && (
              <UploadFolder
                visible={uploadFolderVisible}
                selectAT={selectAT}
                onClose={closeUploadFloderDialog}
              />
            )}
          </>
        ),
        [uploadFolderVisible, activeStandardized]
      )}
    </div>
  );
};

export default observer(PageList);
